import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Form, Input, Button, DatePicker, Select, message, Card, Divider } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import moment from 'moment';
import api from '../utils/api';
import Header from '../components/Header';
import useTheme from '../hooks/useTheme';

const { Option } = Select;
const { TextArea } = Input;

const AddVersionPage = () => {
  const { id: projectId } = useParams();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [project, setProject] = useState(null);
  const [darkMode, setDarkMode] = useTheme();

  // 获取项目信息
  useEffect(() => {
    const fetchProjectDetails = async () => {
      try {
        if (projectId) {
          const response = await api.get(`/api/project/${projectId}`);
          if (response.data && response.data.code === '200') {
            setProject(response.data.data);
          } else {
            message.error('获取项目信息失败: ' + (response.data?.message || '未知错误'));
          }
        }
      } catch (error) {
        console.error('获取项目信息失败:', error);
        message.error('获取项目信息失败: ' + (error.message || '未知错误'));
      }
    };

    fetchProjectDetails();
  }, [projectId]);

  // 提交表单
  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      // 格式化日期
      const formattedValues = {
        ...values,
        projectId: projectId, // 这里保持 projectId 不变，因为这是 API 需要的字段名
        releaseDate: values.releaseDate ? values.releaseDate.format('YYYY-MM-DD') : null,
        changes: values.changes ? values.changes.split('\n').filter(item => item.trim() !== '') : []
      };

      console.log('提交版本数据:', formattedValues);

      // 发送请求
      const response = await api.post('/api/version/create', formattedValues);
      
      if (response.data && (response.data.code === 200 || response.data.code === '200')) {
        message.success('版本创建成功');
        // 返回项目详情页
        navigate(`/project/${projectId}`);
      } else {
        message.error(response.data?.message || '创建失败，请重试');
      }
    } catch (error) {
      console.error('创建版本失败:', error);
      message.error('创建失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  // 返回项目详情页
  const goBack = () => {
    navigate(`/project/${projectId}`);
  };

  return (
    <div className={`app-container ${darkMode ? 'dark-mode' : ''}`}>
      <Header darkMode={darkMode} setDarkMode={setDarkMode} />
      
      <div className="content-container" style={{ padding: '2rem 5%', marginTop: '64px' }}>
        <Card 
          title={
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                type="text" 
                icon={<ArrowLeftOutlined />} 
                onClick={goBack}
                style={{ marginRight: '10px' }}
              />
              <span>新增版本</span>
            </div>
          }
          style={{ maxWidth: '800px', margin: '0 auto' }}
        >
          {project && (
            <div className="project-info" style={{ marginBottom: '20px' }}>
              <h3>{project.name}</h3>
              <p>当前状态: {project.status}</p>
            </div>
          )}
          
          <Divider />
          
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              versionType: 'feature',
              status: 'stable'
            }}
          >
            <Form.Item
              name="versionNumber"
              label="版本号"
              rules={[{ required: true, message: '请输入版本号' }]}
            >
              <Input placeholder="例如: 1.0.0" />
            </Form.Item>
            
            <Form.Item
              name="versionType"
              label="版本类型"
              rules={[{ required: true, message: '请选择版本类型' }]}
            >
              <Select>
                <Option value="feature">功能版本</Option>
                <Option value="patch">修复版本</Option>
                <Option value="pre-release">预发布版本</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="releaseDate"
              label="发布日期"
              rules={[{ required: true, message: '请选择发布日期' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
            
            <Form.Item
              name="status"
              label="版本状态"
              rules={[{ required: true, message: '请选择版本状态' }]}
            >
              <Select>
                <Option value="stable">稳定版</Option>
                <Option value="beta">测试版</Option>
                <Option value="alpha">内测版</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="changes"
              label="更新内容"
              rules={[{ required: true, message: '请输入更新内容' }]}
            >
              <TextArea 
                rows={6} 
                placeholder="请输入更新内容，每行一条，例如:&#10;1. 新增用户管理功能&#10;2. 修复登录页面bug&#10;3. 优化页面加载速度" 
              />
            </Form.Item>
            
            <Form.Item
              name="description"
              label="版本描述"
            >
              <TextArea rows={4} placeholder="请输入版本描述（选填）" />
            </Form.Item>
            
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading} block>
                提交
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default AddVersionPage;
